package band.wukong.practice.javase.core.io.stream;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;

/**
 * Desc:
 * Author: sunjs
 * Date: 2009-11-12 16:12:54
 */
public class TestFileStream {
    //    static final String FILE_IN = "E:\\somecode\\TestJava\\src\\com\\jsun\\javase\\io\\doc\\poem.txt";
    static final String FILE_IN = "E:\\workspace\\TestJava\\src\\com\\jsun\\javase\\io\\doc\\poem.txt";
    static final String FILE_OUT = "E:\\workspace\\TestJava\\src\\com\\jsun\\javase\\io\\doc\\out.txt";

    public static void main(String[] args) throws Exception {
        testInAndOut();

    }

    public static void testInputStream() throws Exception {
        //InputStream->FileInputStream
        InputStream is = new FileInputStream(FILE_IN);
//      三种定义byteArray不同，输出时运行的状态也不同。
//            byte[] byteArray = new byte[200];
//            byte[] byteArray = new byte[1024];
        byte[] byteArray = new byte[is.available()];
        is.read(byteArray);
        System.out.print(new String(byteArray));
        //TODO [Optimization]能否改成按指定字节分步读取
        is.close();
    }

    public static void testOutputStream() throws Exception {
        //OutputStream->FileOutputStream
        FileOutputStream os = new FileOutputStream(FILE_OUT, true); //注意：true代表append
        String str = "AntiJapanCN@gmail.com\n";
        byte[] byteArray = str.getBytes();
        os.write(byteArray);
        os.close();
    }

    public static void testInAndOut() throws Exception {
        final int SIZE = 2;
        FileInputStream in = new FileInputStream(FILE_IN);
        FileOutputStream out = new FileOutputStream(FILE_OUT);

        byte[] buff = new byte[SIZE];   //创建字节数组缓冲区

        int len = in.read(buff);    //把文件的中的书籍独到buff中
        int i = 0;
        while (len != -1) {
            out.write(buff, 0, len);
            len = in.read(buff);
            i++;
        }
        System.out.println("i = " + i);
        in.close();
        out.close();
    }
}